package com.sciai.exception;

import cn.com.sciai.aix.common.http.SciaiHttpResponseEntity;
import cn.com.sciai.aix.common.http.SciaiHttpResponseEntityBuilder;
import cn.com.sciai.aix.common.http.util.HttpServletRequestUtil;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.util.validation.ValidationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO lb <类名>
 *
 * @author libin
 * @version 1.0.0.0
 * <p>Title: GlobalExceptionHandler </p>
 * <p>Description: TODO lb </p>
 * Package: com.sciai.exception
 * Company: 沪渝研究院
 * Copyright: Copyright(c) AI+X
 * Date: 2023年03月07日 17:14
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public SciaiHttpResponseEntity handleRRException(BusinessException e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("业务异常", e);
        return SciaiHttpResponseEntityBuilder.builder().error(e.getCode() + "", e.getMsg()).build();
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public SciaiHttpResponseEntity handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("方法参数类型不匹配", e);
        return SciaiHttpResponseEntityBuilder.builder().error("方法参数类型不匹配").build();
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public SciaiHttpResponseEntity handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("缺少请求参数", e);
        return SciaiHttpResponseEntityBuilder.builder().error("缺少请求参数").build();
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public SciaiHttpResponseEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("参数解析失败", e);
        return SciaiHttpResponseEntityBuilder.builder().error("参数解析失败").build();
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public SciaiHttpResponseEntity handleValidationException(ValidationException e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("参数验证失败", e);
        return SciaiHttpResponseEntityBuilder.builder().error("参数验证失败").build();
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public SciaiHttpResponseEntity handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("不支持当前请求方法", e);
        return SciaiHttpResponseEntityBuilder.builder().error("不支持当前请求方法").build();
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public SciaiHttpResponseEntity handleHttpMediaTypeNotSupportedException(Exception e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("不支持当前媒体类型", e);
        return SciaiHttpResponseEntityBuilder.builder().error("不支持当前媒体类型").build();
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public SciaiHttpResponseEntity handleDuplicateKeyException(DuplicateKeyException e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error(e.getMessage(), e);
        return SciaiHttpResponseEntityBuilder.builder().error("500", "数据库中已存在该记录").build();
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public SciaiHttpResponseEntity handleMaxSizeException(MaxUploadSizeExceededException e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error(e.getMessage(), e);
        return SciaiHttpResponseEntityBuilder.builder().error("500", "File too large!").build();
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(NotLoginException.class)
    public SciaiHttpResponseEntity handleNotLoginException(NotLoginException e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error(e.getMessage(), e);
        return SciaiHttpResponseEntityBuilder.builder().error("401", e.getMessage()).build();
    }

    @ExceptionHandler(SaTokenException.class)
    public SciaiHttpResponseEntity handleMaxSizeException(SaTokenException e) {
        log.error(e.getMessage(), e);
        log.error("uri：{}, httpMethod:{}, errMsg:{}", HttpServletRequestUtil.getRequestURI(), HttpServletRequestUtil.getRequest().getMethod(), e.getMessage());
        return SciaiHttpResponseEntityBuilder.builder().error("403", e.getMessage()).build();
    }

    /**
     * 验证bean类型
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public SciaiHttpResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        List<String> result = new ArrayList<>();
        e.getBindingResult().getFieldErrors().forEach((fieldError) -> {
//            result.add(Dict.create().set("field", fieldError.getField()).set("msg", fieldError.getDefaultMessage()));
            result.add(fieldError.getDefaultMessage());
        });
        return SciaiHttpResponseEntityBuilder.builder().error("500", result.toString()).build();
    }


    /**
     * 兜底验证ValidationException
     */
    @ExceptionHandler(javax.validation.ValidationException.class)
    public SciaiHttpResponseEntity handleValidationException(javax.validation.ValidationException e) {
        log.error(e.getMessage(), e);
        return SciaiHttpResponseEntityBuilder.builder().error("500", e.getCause().getMessage()).build();
    }


    @ExceptionHandler(NoHandlerFoundException.class)
    public SciaiHttpResponseEntity handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return SciaiHttpResponseEntityBuilder.builder().error("404", "路径不存在，请检查路径是否正确").build();
    }

    @ExceptionHandler(Exception.class)
    public SciaiHttpResponseEntity handleException(Exception e) {
        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error(e.getMessage(), e);
        return SciaiHttpResponseEntityBuilder.builder().error("500", "服务器异常").build();
    }

    @ExceptionHandler(value = KaptchaException.class)
    public SciaiHttpResponseEntity kaptchaExceptionHandler(KaptchaException kaptchaException) {
        if (kaptchaException instanceof KaptchaIncorrectException) {
            return SciaiHttpResponseEntityBuilder.builder().error("500", "验证码不正确").build();
        } else if (kaptchaException instanceof KaptchaNotFoundException) {
            return SciaiHttpResponseEntityBuilder.builder().error("500", "验证码未找到").build();
        } else if (kaptchaException instanceof KaptchaTimeoutException) {
            return SciaiHttpResponseEntityBuilder.builder().error("500", "验证码过期,请重新获取验证码").build();
        } else {
            return SciaiHttpResponseEntityBuilder.builder().error("500", "验证码渲染失败").build();
        }

    }
}
